package com.mcy.threed.jpct;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import com.mcy.study.R;
import com.mcy.threed.jpct.movement.Movement;
import com.mcy.threed.jpct.movement.MovementHandler;
import com.threed.jpct.Camera;
import com.threed.jpct.FrameBuffer;
import com.threed.jpct.Loader;
import com.threed.jpct.Matrix;
import com.threed.jpct.Object3D;
import com.threed.jpct.RGBColor;
import com.threed.jpct.SimpleVector;
import com.threed.jpct.Texture;
import com.threed.jpct.TextureManager;
import com.threed.jpct.World;
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class JpctLoadModelActivity extends Activity implements OnClickListener{
	GLSurfaceView mGlView;
	ModelRenderer mRenderer;
	MovementHandler mMovementHandler;
//	private float touchX;
//	private float moveX;
//	private float moveY;
//	private float touchY;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.e("test", "create");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_jpct_model);
		LinearLayout container = (LinearLayout)findViewById(R.id.container);
		mMovementHandler = new MovementHandler();
	    mGlView = new GLSurfaceView(this);
	    mRenderer = new ModelRenderer();
		mGlView.setRenderer(mRenderer);
		container.addView(mGlView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		findViewById(R.id.button1).setOnClickListener(this);
		findViewById(R.id.button2).setOnClickListener(this);
		findViewById(R.id.button3).setOnClickListener(this);
		findViewById(R.id.button4).setOnClickListener(this);
		findViewById(R.id.button5).setOnClickListener(this);
		findViewById(R.id.button6).setOnClickListener(this);
		}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
//		switch (event.getAction()) {
//		case MotionEvent.ACTION_DOWN:
//			touchX = event.getX();
//			touchY = event.getY();
//			break;
//		case MotionEvent.ACTION_UP:
//			moveX = 0;
//			moveY = 0;
//			break;
//		case MotionEvent.ACTION_MOVE:
//			moveX = event.getX()-touchX;
//			moveY = event.getY()-touchY;
//			touchX = event.getX();
//			touchY = event.getY();
//			mRenderer.touchTurn = moveX / -100f;
//			mRenderer.touchTurnUp = moveY / -100f;
//			break;
//		default:
//			break;
//		}
		mMovementHandler.handleMotionEvent(event);
		Movement movement = mMovementHandler.getMovement();
		mRenderer.moveCamera(movement);
		return super.onTouchEvent(event);
	}

	@Override
	protected void onResume() {
		Log.e("test", "resume");
		super.onResume();
		mGlView.onResume();
	}

	@Override
	protected void onPause() {
		Log.e("test", "pause");
		super.onPause();
		mGlView.onPause();
	}
	
	@Override
	protected void onDestroy() {
		Log.e("test", "destory");
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
        switch (v.getId()) {
		case R.id.button1:
			mRenderer.moveIn(50f);
			break;
		case R.id.button2:
			mRenderer.moveOut(50f);
			break;
		case R.id.button3:
			mRenderer.moveLeft(50f);
			break;
		case R.id.button4:
			mRenderer.moveUp(50f);
			break;
		case R.id.button5:
			mRenderer.moveDown(50f);
			break;
		case R.id.button6:
			mRenderer.moveRight(50f);
			break;
		default:
			break;
		}		
	}
	
	//渲染器
	class ModelRenderer implements Renderer{
		//纹理数组
		private String[] textures = {"skin"};
		//scale加载比例
		private int modScale = 1;
//		//模型显示比例
//		private float curScale = 1;
//		//模型改变比例
//		private float changeScale = 1;
		//模型旋转角度
		private float touchTurn = 0;
		private float touchTurnUp = 0;
		//相机移动速度
		private float moveOutSpeed = 0;
		private float moveInSpeed = 0;
		private float moveLSpeed = 0;
		private float moveRSpeed = 0;
		private float moveUpSpeed = 0;
		private float moveDownSpeed = 0;
		
		private World world;
		private FrameBuffer fb;
		
		private Object3D mod;
		
		public ModelRenderer(){
			//将纹理数组中的名字添加到TextureManger
			for(int i=0;i<textures.length;i++){
				if(!TextureManager.getInstance().containsTexture(textures[i])){
					Texture texture = new Texture(ResourceLoader.loadBitmap(getResources(), R.drawable.expo_stones2));
					TextureManager.getInstance().addTexture(textures[i],texture);
				}
			}
		}
		
		@Override
		public void onSurfaceCreated(GL10 gl, EGLConfig config) {
			Log.e("modrender", "surface create");
			world = new World();
			//设置环境光
			world.setAmbientLight(150, 150, 150);
			//加载模型
			mod = loadModel("cia_mesh.3ds", modScale);
			//设置纹理
			mod.setTexture(textures[0]);
			//创建
			mod.build();
			//添加到world中
			world.addObject(mod);
			//调整坐标系
			world.getCamera().setPosition(5, 0,-5);
			//调整相机
			world.getCamera().lookAt(mod.getTransformedCenter());
		}

		@Override
		public void onSurfaceChanged(GL10 gl, int width, int height) {
			Log.e("modrender", "surface changed");
			if(fb!=null){
				fb=null;
			}
			fb = new FrameBuffer(gl, width, height);
		}

		@Override
		public void onDrawFrame(GL10 gl) {
			//以黑色清除屏幕
			fb.clear(RGBColor.BLACK);
			//模型缩放
//			mod.scale(changeScale);
//			curScale = curScale*changeScale;
//			changeScale = 1;
			//旋转模型角度
			if(touchTurn!=0){
				mod.rotateX(touchTurn);
				touchTurn = 0;
			}
			if(touchTurnUp!=0){
				mod.rotateY(touchTurnUp);
				touchTurnUp=0;
			}
			//调整相机相机
			Camera camera = world.getCamera();
			if(moveOutSpeed != 0){
				camera.moveCamera(Camera.CAMERA_MOVEOUT, moveOutSpeed);
				moveOutSpeed = 0;
			}
			if(moveInSpeed!=0){
				camera.moveCamera(Camera.CAMERA_MOVEIN, moveInSpeed);
				moveInSpeed = 0;	
			}
            if(moveLSpeed!=0)
            {
    			camera.moveCamera(Camera.CAMERA_MOVELEFT, moveLSpeed);
    			moveLSpeed = 0;
            }
            if(moveRSpeed!=0)
            {
    			camera.moveCamera(Camera.CAMERA_MOVERIGHT, moveRSpeed);
    			moveRSpeed = 0;
            }
            if(moveUpSpeed!=0)
            {
    			camera.moveCamera(Camera.CAMERA_MOVEUP, moveUpSpeed);
    			moveUpSpeed = 0;
            }
            if(moveDownSpeed!=0)
            {
    			camera.moveCamera(Camera.CAMERA_MOVEDOWN, moveDownSpeed);
    			moveDownSpeed = 0;
            }
			//渲染场景
			world.renderScene(fb);
			//绘制到fb
			world.draw(fb);
			//展示绘制结果
			fb.display();
			//复位更改比例
			
		}
		
		private Object3D loadModel(String filename,int scale){
			Object3D[] model = Loader.load3DS(ResourceLoader.loadFile(getResources(), filename), scale);
			Object3D o3d = new Object3D(0);
			Object3D temp = null;
			for(int i=0;i<model.length;i++){
				temp = model[i];
				//设置中心为原点origon(0,0,0)
				temp.setCenter(SimpleVector.ORIGIN);
				
				//沿X轴抓换坐标系到正常坐标系，（jpct-ae中y,z反的）
				//temp.rotateX((float)(0.5*Math.PI));?
				
				//使用旋转后矩阵作为对象旋转网格的原始数据
				temp.rotateMesh();
				//设置新的旋转矩阵
				temp.setRotationMatrix(new Matrix());
				//合并o3d和temp
				o3d = Object3D.mergeObjects(o3d, temp);
				//完成（pc上为build）
				o3d.compile();
			}
			return o3d;
		}
		
		private void moveCamera(Movement movement) {

			if (movement.hasMovement()) {
				Camera camera = world.getCamera();

				Matrix rot = camera.getBack();

				rot.rotateAxis(rot.getYAxis(), -(float) movement.cameraRotationY);
				mod.rotateX(movement.worldRotationX);
				float angle = mod.getYAxis().calcAngle(
						new SimpleVector(0, 1, 0));
				float crossAngle = mod.getYAxis().calcCross(
						new SimpleVector(0, 1, 0)).x;
				if (crossAngle > 0) {
					mod.rotateX(-angle);
				} else {
					float delta = (float) (angle - (Math.PI / 2));
					if (delta > 0) {
						mod.rotateX(delta);
					}
				}
				camera.moveCamera(Camera.CAMERA_MOVELEFT, movement.cameraMovementX);
				camera.moveCamera(Camera.CAMERA_MOVEUP, movement.cameraMovementY);
				camera.moveCamera(Camera.CAMERA_MOVEIN, movement.cameraMovementZ);
			}
		}
		
		public synchronized void moveIn(float speed){
			moveInSpeed = speed;
		}
		public synchronized void moveOut(float speed){
			moveOutSpeed = speed;
		}
		public synchronized void moveLeft(float speed){
			moveLSpeed = speed;
		}
		public synchronized void moveRight(float speed){
			moveRSpeed = speed;
		}
		public synchronized void moveUp(float speed){
			moveUpSpeed = speed;
		}
		public synchronized void moveDown(float speed){
			moveDownSpeed = speed;
		}
	}

}
